<template>
    <div class="index">
        <div
            class="flex-row justify-content-start align-items-center"
            style="width:80%;margin:0 auto;"
        >
            <el-button
                type="warning"
                :disabled="!isVerificationPermission"
                @click="innerVisible = true;getMemberCollectionList()"
            >收藏列表</el-button>

            <div class="dropdown-menu">
                <el-dropdown>
                    <el-button type="primary">
                        指令教程
                        <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown" style="height:300px;overflow-y: auto;">
                        <el-dropdown-item v-for="(item,index) in CourseList" :key="index">
                            <a
                                :href="item.url"
                                target="_blank"
                                rel="noopener noreferrer"
                                style="color:#409eff;text-decoration: none;"
                            >{{item.name}}</a>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="dropdown-menu">
                <el-dropdown>
                    <el-button type="primary">
                        优选公式
                        <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown" style="height:300px;overflow-y: auto;">
                        <el-dropdown-item v-for="(item,index) in preferredFormula" :key="index">
                            <div
                                class="remark"
                                style="width:600px;"
                                @click="testandverify(index,'free')"
                            >{{item.show_formula}}</div>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>
        <div class="formula-textarea">
            <div>
                <el-input
                    type="textarea"
                    :rows="17"
                    placeholder="请在这里输入公式"
                    v-model="formulaVerification"
                ></el-input>
                <div
                    class="tips flex-column justify-content-center"
                    v-if="!isVerificationPermission"
                >
                    <p>请至“会员等级”页开通会员方可使用该功能</p>
                    <router-link class="leave-for" to="/vip-level" repalce>立即前往开通</router-link>
                </div>
            </div>
        </div>
        <div class="btns flex-row justify-content-around align-items-center">
            <el-button
                type="primary"
                :disabled="!isVerificationPermission"
                @click="stickyOrEnd"
                style="width:70px;padding-left:0;padding-right:0;text-align:center;"
            >置顶/置底</el-button>
            <el-button
                type="primary"
                :disabled="!isVerificationPermission"
                @click="verification"
            >批量验证</el-button>
            <el-button
                type="danger"
                :disabled="!isVerificationPermission"
                @click="formulaVerification ='';formulaTextarea=''"
            >清空</el-button>
            <el-button
                :disabled="!isVerificationPermission"
                v-clipboard:copy="copyTxt"
                v-clipboard:success="onCopy"
                v-clipboard:error="onError"
                style="background:#ff9000;color:#fff;"
            >复制结果</el-button>
            <el-button
                type="info"
                :disabled="!isVerificationPermission"
                @click="showRecordingDialog"
            >验证记录</el-button>
            <el-button
                type="success"
                :disabled="!isVerificationPermission"
                @click="clickCollectionFormula"
                v-if="formulaVerification!=''"
            >{{isCollection?'已收藏':'收藏公式'}}</el-button>
            <!-- clickCollectionFormula -->
            <!-- <el-button type="success" :disabled="!isVerificationPermission" @click=""</el-button> -->
        </div>
        <div
            class="formula-textarea"
            v-loading="loading"
            element-loading-text="公式验证中，请稍等。。。"
            element-loading-spinner="el-icon-loading"
        >
            <el-input
                type="textarea"
                disabled
                :rows="20"
                placeholder="验证结果区"
                v-model="formulaTextarea"
                v-show="formulaTextarea==''"
                style="text-align: left;"
            ></el-input>
            <div
                v-html="formulaTextarea"
                ref="copy"
                style="white-space: pre-line;text-align: left;"
                class="result"
                v-show="formulaTextarea"
                disabled
            ></div>
        </div>
        <!-- 收藏公式弹窗 -->
        <el-dialog
            width="50%"
            title="已收藏的公式"
            :visible.sync="innerVisible"
            @close="innerVisible = false"
            append-to-body
        >
            <el-dialog width="50%" title="修改备注" :visible.sync="changeRemarkVisible" append-to-body>
                <el-input v-model="remarkinput" placeholder="请输入备注"></el-input>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="changeRemarkVisible = false">取 消</el-button>
                    <el-button type="primary" @click="upRemaker">确 定</el-button>
                </span>
            </el-dialog>
            <div>
                <div
                    v-for="(item,index) in memberCollectionData"
                    :key="index"
                    class="flex-row justify-content-between align-items-center"
                >
                    <span
                        class="remark"
                        style="width:80%"
                        @click="testandverify(index)"
                    >{{item.show_formula}}</span>
                    <div>
                        <el-button
                            style="padding: 3px 0"
                            type="text"
                            @click="showChangeRemarkVisible(item.id)"
                        >修改备注</el-button>
                        <el-button
                            style="padding: 3px 0;color:red;"
                            type="text"
                            @click="delCollection(item.id)"
                        >删除公式</el-button>
                    </div>
                </div>
                <div class="pagination">
                    <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="this.meta.total"
                        :page-size="this.meta.per_page"
                        @current-change="handleCurrentChange"
                        v-show="memberCollectionData.length"
                    ></el-pagination>
                </div>
            </div>
        </el-dialog>
        <!-- <el-dialog title="提示" :visible.sync="formulaDialog" width="50%" center>

      <div style="text-align:center;font-size:22px;">
        <i class="el-icon-info" style="color:red;"></i>
        查看已收藏公式或收藏当前验证公式
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clickCollectionFormula" round v-if="formulaVerification!=''">收 藏</el-button>
        <el-button type="primary" @click="innerVisible = true;getMemberCollectionList()" round>查 看</el-button>
        <el-button type="danger" @click="formulaDialog = false" round>取 消</el-button>
      </span>
        </el-dialog>-->
        <!-- 验证记录弹窗 -->
        <el-dialog title="验证记录" :visible.sync="recordingDialog" width="50%" center>
            <div>
                <div
                    v-for="(item,index) in recordingList"
                    :key="index"
                    class="flex-row justify-content-between align-items-center"
                >
                    <span
                        class="remark"
                        style="width:80%"
                        @click="testandverify(index,'recording')"
                    >{{item.show_formula}}</span>
                    <el-button
                        style=" padding: 3px 0;color:red;"
                        type="text"
                        @click="delverification(item.id)"
                    >删除记录</el-button>
                </div>
                <div class="pagination">
                    <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="this.meta.total"
                        :page-size="this.meta.per_page"
                        @current-change="handleCurrentChangeRecording"
                        v-show="recordingList.length"
                    ></el-pagination>
                </div>
            </div>
        </el-dialog>
        <div class="mask-v" v-if="verificationLoading"></div>
    </div>
</template>

<script>
export default {
  props: {},
  data () {
    return {
      formulaVerification: '',
      formulaTextarea: '',
      isVerificationPermission: true, // 验证权限是否开通
      loading: false,
      copyTxt: '',
      CourseList: [],
      formulaDialog: false,
      innerVisible: false,
      memberCollectionData: [],
      sort: 'DESC',
      changeRemarkVisible: false,
      meta: { current_page: 1, per_page: 10 },
      remarkinput: '',
      collection_id: '',
      recordingDialog: false,
      recordingList: [],
      verificationLoading: false,
      record_id: '',
      collect_id: '',
      preferredFormula: [],
      isCollection: false,
      formula_id: ''
    }
  },
  computed: {},
  created () {
    this.getFunction()
    this.getCourseList()
    this.getPreferredFormula()
  },
  mounted () {},
  watch: {},
  methods: {
    stickyOrEnd () {
      let scrollHeight = this.$refs.copy.scrollHeight
      // console.log(1111);
      console.log(this.$refs.copy.scrollTop)
      console.log(scrollHeight)

      if (this.$refs.copy.scrollTop > 0) {
        this.$refs.copy.scrollTop = 0
      } else {
        this.$refs.copy.scrollTop = scrollHeight
      }
    },
    showRecordingDialog () {
      this.meta.current_page = 1
      this.getVerificationGetlist()
      this.recordingDialog = !this.recordingDialog
    },
    testandverify (index, type) {
      if (!this.isVerificationPermission) {
        this.$message.closeAll()
        this.$message.error('请先开通验证权限！')
        return
      }
      this.loading = !this.loading
      this.verificationLoading = true
      // this.loading = true
      if (type === 'recording') {
        this.recordingDialog = false
        this.record_id = this.recordingList[index].id
        this.collect_id = ''
        this.getVerificationDetail(this.recordingList[index].id)
      } else if (type === 'free') {
        this.record_id = ''
        this.collect_id = ''
        this.formula_id = this.preferredFormula[index].id
        this.getFreeDetail(this.preferredFormula[index].id)
      } else {
        // this.formulaVerification = this.memberCollectionData[index].formula;
        this.record_id = ''
        this.collect_id = this.memberCollectionData[index].id
        this.getCollectDetail(this.memberCollectionData[index].id)
      }
    },
    // 获取优选公式详情
    getFreeDetail (id) {
      let rsaStr = `id=${id}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .getFreeDetailFormula(rsaCode)
          .then(res => {
            if (res.data.errno === '000') {
              this.formulaVerification =
                                res.data.result.data.formula
              this.verificationFormula()
            }
          })
          .catch(err => {})
      })
    },
    // 收藏记录详情
    getCollectDetail (id) {
      let rsaStr = `id=${id}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .getMemberCollectionDetail(rsaCode)
          .then(res => {
            if (res.data.errno === '000') {
              this.formulaDialog = false
              this.innerVisible = false
              this.formulaVerification =
                                res.data.result.data.formula
              this.verificationFormula()
            }
          })
          .catch(err => {})
      })
    },
    // 验证记录详情
    getVerificationDetail (id) {
      let rsaStr = `id=${id}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .GETVerificationDetail(rsaCode)
          .then(res => {
            if (res.data.errno === '000') {
              this.recordingDialog = false
              this.formulaVerification =
                                res.data.result.data.formula
              this.verificationFormula()
            }
          })
          .catch(err => {})
      })
    },
    upRemaker () {
      if (this.remarkinput !== '') {
        this.editRemak()
      }
    },
    delCollection (id) {
      this.meta.current_page = 1
      this.collection_id = id
      this.deleteCollection()
    },
    delverification (id) {
      this.meta.current_page = 1
      this.collection_id = id
      this.DELETEverification()
    },
    showChangeRemarkVisible (id) {
      // console.log(id);
      this.remarkinput = ''
      this.changeRemarkVisible = true
      this.collection_id = id
    },
    verification () {
      // var str = this.formulaVerification.replace(/\-/gm, "_-");
      // str = this.formulaVerification.replace(/\+/gm, "_");
      // str = this.formulaVerification.replace(/\=/gm, "*");
      if (this.formulaVerification) {
        // this.formulaVerification = str;
        // //console.log(str);
        this.loading = true
        this.verificationLoading = true
        this.verificationFormula()
      }
    },
    handleCurrentChange (val) {
      this.meta.current_page = val
      this.getMemberCollectionList()
    },
    handleCurrentChangeRecording (val) {
      this.meta.current_page = val
      this.getVerificationGetlist()
    },
    onCopy () {
      // //console.log(this.$refs.copy.innerText)
      this.$message.closeAll()
      this.$message.success('复制成功')
    },
    onError () {
      this.$message.closeAll()
      this.$message.error('复制失败，请重试')
    },
    clickCollectionFormula () {
      if (this.formulaVerification !== '' && !this.isCollection) {
        this.collectionFormula()
      }
    },
    collectionFormula () {
      let params = {
        formula: this.formulaVerification
      }
      this.http
        .collectionFormula(params)
        .then(res => {
          this.$message.closeAll()
          if (res.data.errno === '000') {
            this.$message.success(res.data.errmsg)
            this.isCollection = true
          } else {
            this.$message.error(res.data.errmsg)
          }
        })
        .catch(err => {
          // console.log(err);
        })
    },
    getFunction () {
      let rsaStr = `uuid=${sessionStorage.getItem('u')}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .getUserInfo(rsaCode)
          .then(res => {
            if (res.data.errno === '000') {
              // console.log(Number(new Date(res.data.result.data.grade_expire_time)),Number(new Date()))
              console.log(Date.parse(new Date()))
              let str = res.data.result.data.grade_expire_time.replace(
                /\-/gm,
                '/'
              )
              console.log(Date.parse(new Date(str)))
              this.isVerificationPermission =
                                res.data.result.data.level == 0
                                  ? false
                                  : Date.parse(new Date(str)) -
                                          Date.parse(new Date()) >
                                      0
            }
          })
          .catch(err => {})
      })
    },
    verificationFormula () {
      let regStr = this.formulaVerification
      regStr = regStr.replace(/\-/gm, '_-')
      regStr = regStr.replace(/\+/gm, '_')
      regStr = regStr.replace(/\=/gm, '*')
      // console.log(regStr);
      let params = {
        instructions:
                    this.record_id !== '' ||
                    this.collect_id !== '' ||
                    this.formula_id !== ''
                      ? ''
                      : regStr,
        record_id: this.record_id,
        collect_id: this.collect_id,
        formula_id: this.formula_id
      }
      this.http
        .formula(params)
        .then(res => {
          this.loading = false
          this.verificationLoading = false
          this.record_id = ''
          this.collect_id = ''
          this.formula_id = ''
          if (res.data.errno === '000') {
            // //console.log(res.data.result.data.kj_arr)
            this.isCollection = res.data.result.data.collected
            if (!res.data.result.data.kj_arr) {
              let str = res.data.result.data.kj_str.replace(
                /\\n/gm,
                '<br/>'
              )
              this.formulaTextarea = str
            } else {
              let str =
                                res.data.result.data.kj_str_head + '<br/>'
              res.data.result.data.kj_arr.forEach(
                (element, index) => {
                  // //console.log(element)
                  str = str + '<br/>' + element.kj
                  // this.formulaTextarea = str;
                  if (
                    index + 1 ===
                                        res.data.result.data.kj_arr.length
                  ) {
                    str =
                                            str +
                                            '<br/><br/><br/>' +
                                            res.data.result.data.kj_str
                    this.formulaTextarea = str.replace(
                      /\\n/gm,
                      '<br/>'
                    )
                  }
                }
              )
              // //console.log(str)
            }
            setTimeout(() => {
              this.copyTxt = this.$refs.copy.innerText
            }, 1000)
          } else {
            this.$message.closeAll()
            this.$message.error(res.data.errmsg)
          }
        })
        .catch(err => {
          // console.log(err);
        })
    },
    // 指令教程
    getCourseList () {
      this.http
        .getCourseList()
        .then(res => {
          if (res.data.errno === '000') {
            this.CourseList = res.data.result.data
          }
        })
        .catch(err => {})
    },
    // 获取优选公式
    getPreferredFormula () {
      this.http
        .getPreferred()
        .then(res => {
          if (res.data.errno === '000') {
            this.preferredFormula = res.data.result.data
          }
        })
        .catch(err => {})
    },
    // 获取用户收藏列表
    getMemberCollectionList () {
      let rsaStr = `uuid=${sessionStorage.getItem('u')}&page=${
        this.meta.current_page
      }&page_size=${this.meta.per_page}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .getMemberCollectionList(rsaCode)
          .then(res => {
            if (res.data.errno === '000') {
              this.memberCollectionData = res.data.result.data
              this.meta = res.data.result.meta
            }
          })
          .catch(err => {})
      })
    },
    editRemak () {
      let rsaStr = `collection_id=${this.collection_id}&remark=${this.remarkinput}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .editRemak(rsaCode)
          .then(res => {
            this.$message.closeAll()
            if (res.data.errno === '000') {
              this.$message.success(res.data.errmsg)
              this.changeRemarkVisible = false
              this.getMemberCollectionList()
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
          .catch(err => {})
      })
    },
    deleteCollection () {
      let rsaStr = `collection_id=${this.collection_id}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .deleteCollection(rsaCode)
          .then(res => {
            this.$message.closeAll()
            if (res.data.errno === '000') {
              this.$message.success(res.data.errmsg)
              this.getMemberCollectionList()
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
          .catch(err => {})
      })
    },
    DELETEverification () {
      let rsaStr = `id=${this.collection_id}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .DELETEverification(rsaCode)
          .then(res => {
            this.$message.closeAll()
            if (res.data.errno === '000') {
              this.$message.success(res.data.errmsg)
              this.getVerificationGetlist()
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
          .catch(err => {})
      })
    },
    getVerificationGetlist () {
      let rsaStr = `uuid=${sessionStorage.getItem('u')}&page=${
        this.meta.current_page
      }&page_size=${this.meta.per_page}`
      this.$getCode(rsaStr).then(rsaCode => {
        this.http
          .GETVerificationGetlist(rsaCode)
          .then(res => {
            if (res.data.errno === '000') {
              this.recordingList = res.data.result.data
              this.meta = res.data.result.meta
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
          .catch(err => {})
      })
    }
  },
  components: {}
}
</script>

<style scoped lang="less">
@import url("./index.less");
</style>
<style scoped>
.remark {
    display: inline-block;
    width: 50%;
    height: 40px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
    line-height: 40px;
}
.el-pagination {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}
</style>
